import json

from rest_framework import serializers

from .models import *

read_only = ['reviewer', 'revstatus', 'created_time', 'review_time']


# 基序列化器类
class BaseCompetitionSerializer(serializers.ModelSerializer):
    class Meta:
        fields = "__all__"
        read_only_fields = read_only  # 确保read_only是一个有效的变量或在使用前定义它

    def validate_authors(self, authors):
        """
                    authors示例：
                    [
                      {
                        'account':'23432',
                        'role':'主讲人',
                      },
                      {
                        'account':'34',
                        'role':'打杂',
                      },
                      {
                        'account':'3434',
                        'role':'打杂',
                      }
                    ]
                    """
        # 如果authors不满足上述注释中示例的格式要求
        # 验证authors是否为列表
        if not isinstance(authors, list):
            return "Error: authors 必须是json列表"

            # 遍历列表中的每个作者信息
        for author in authors:
            # 验证每个作者信息是否为字典
            if not isinstance(author, dict):
                raise Exception("Error: 每一个 author 必须是字典")

                # 验证字典中是否包含'account'和'role'键，且它们的值不为空
            if 'account' not in author or not author['account']:
                raise Exception("Error: account键是必须的，它存放用户名（字符串）.")

            if 'role' not in author or not author['role']:
                raise Exception("Error: account键是必须的，它存放用户名的角色（字符串）.")
            # 验证字典中是否有name键
            if 'name' not in author or not author['name']:
                raise Exception("Error: name键是必须的，它存放用户名的姓名（字符串）.")

            # 字典中的account role name 必须为字符串
            if not isinstance(author['account'], str):
                raise Exception("Error: Each author's 'account' 必须是字符串.")
            if not isinstance(author['role'], str):
                raise Exception("Error: Each author's 'role' 必须是字符串.")
            if not isinstance(author['name'], str):
                raise Exception("Error: Each author's 'name' 必须是字符串.")

                # 如果authors不是列表或者包含重复元素，则抛出ValidationError
        if not isinstance(authors, list):
            raise ValidationError({'authors': 'authors 必须是列表.'})
        # 可以在这里添加额外的验证逻辑，例如检查作者数量等
        seen_accounts = set()
        for author in authors:
            account = author['account']
            if account in seen_accounts:
                raise serializers.ValidationError("作者账户重复: {}".format(account))
            seen_accounts.add(account)
        return authors

    def validate_score_weights(self, score_weights):
        for value in score_weights:
            if value < 0 or value > 1:
                raise serializers.ValidationError("分数权重值必须在0到1之间")
        # score_weights 中权重和必须为1
        if round(sum(score_weights), 8) != 1:
            raise serializers.ValidationError("分数权重和必须为1")
        return score_weights

    def validate(self, data):
        # 在这里进行跨字段验证
        authors = data.get('authors')
        score_weights = data.get('score_weights')
        if len(score_weights) != len(authors):
            raise serializers.ValidationError("分数权重和作者数量不匹配")

        return data

    def create(self, validated_data):
        report = super().create(validated_data)

        return report

    def update(self, instance, validated_data):
        report = super().update(instance, validated_data)

        return report


class BasicTeachingTaskSerializer(BaseCompetitionSerializer):
    class Meta:
        model = BasicTeachingTask
        fields = "__all__"
        # 假设 read_only 已经在外部定义，它是一个包含只读字段名的列表
        read_only_fields = read_only

        # 检查数据


# TeacherCompetition"序列化
class TeacherCompetitionSerializer(BaseCompetitionSerializer):
    class Meta:
        model = TeacherCompetition
        fields = "__all__"
        read_only_fields = read_only


# Certificate"序列化
class CertificateSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Certificate
        fields = "__all__"
        read_only_fields = read_only


# InnovationProject"序列化
class InnovationProjectSerializer(BaseCompetitionSerializer):
    class Meta:
        model = InnovationProject
        fields = "__all__"
        read_only_fields = read_only


# ResearchProject"序列化
class ResearchProjectSerializer(BaseCompetitionSerializer):
    class Meta:
        model = ResearchProject
        fields = "__all__"
        read_only_fields = read_only


# Competition"序列化
class StudentCompetitionSerializer(BaseCompetitionSerializer):
    class Meta:
        model = StudentCompetition
        fields = "__all__"
        read_only_fields = read_only


# Training"序列化
class TrainingSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Training
        fields = "__all__"
        read_only_fields = read_only


# News"序列化
class NewsSerializer(BaseCompetitionSerializer):
    class Meta:
        model = News
        fields = "__all__"
        read_only_fields = read_only


# Judge"序列化
class JudgeSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Judge
        fields = "__all__"
        read_only_fields = read_only


# EnterpriseVisit"序列化
class EnterpriseVisitSerializer(BaseCompetitionSerializer):
    class Meta:
        model = EnterpriseVisit
        fields = "__all__"
        read_only_fields = read_only


# PartyWork"序列化
class PartyWorkSerializer(BaseCompetitionSerializer):
    class Meta:
        model = PartyWork
        fields = "__all__"
        read_only_fields = read_only


# Recruitment"序列化
class RecruitmentSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Recruitment
        fields = "__all__"
        read_only_fields = read_only


# ProfessionalIntroduction"序列化
class ProfessionalIntroductionSerializer(BaseCompetitionSerializer):
    class Meta:
        model = ProfessionalIntroduction
        fields = "__all__"
        read_only_fields = read_only


# WelcomeWork"序列化
class WelcomeWorkSerializer(BaseCompetitionSerializer):
    class Meta:
        model = WelcomeWork
        fields = "__all__"
        read_only_fields = read_only


# NewTeacherInterview"序列化
class NewTeacherInterviewSerializer(BaseCompetitionSerializer):
    class Meta:
        model = NewTeacherInterview
        fields = "__all__"
        read_only_fields = read_only


# NewTeacherTrain"序列化
class NewTeacherTrainSerializer(BaseCompetitionSerializer):
    class Meta:
        model = NewTeacherTrain
        fields = "__all__"
        read_only_fields = read_only


# ExcellentTalent"序列化
class ExcellentTalentSerializer(BaseCompetitionSerializer):
    class Meta:
        model = ExcellentTalent
        fields = "__all__"
        read_only_fields = read_only


# ExtraInspection"序列化
class ExtraInspectionSerializer(BaseCompetitionSerializer):
    class Meta:
        model = ExtraInspection
        fields = "__all__"
        read_only_fields = read_only


# SchoolMeeting"序列化
class SchoolMeetingSerializer(BaseCompetitionSerializer):
    class Meta:
        model = SchoolMeeting
        fields = "__all__"
        read_only_fields = read_only


# WorkGroup"序列化
class WorkGroupSerializer(BaseCompetitionSerializer):
    class Meta:
        model = WorkGroup
        fields = "__all__"
        read_only_fields = read_only


# Website"序列化
class WebsiteSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Website
        fields = "__all__"
        read_only_fields = read_only


# Activity"序列化
class ActivitySerializer(BaseCompetitionSerializer):
    class Meta:
        model = Activity
        fields = "__all__"
        read_only_fields = read_only


# Course"序列化
class CourseSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Course
        fields = "__all__"
        read_only_fields = read_only


# TemporaryWork"序列化
class TemporaryWorkSerializer(BaseCompetitionSerializer):
    class Meta:
        model = TemporaryWork
        fields = "__all__"
        read_only_fields = read_only


# Participate"序列化
class ParticipateSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Participate
        fields = "__all__"
        read_only_fields = read_only


# Visit"序列化
class VisitSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Visit
        fields = "__all__"
        read_only_fields = read_only


# CrossCourse"序列化
class CrossCourseSerializer(BaseCompetitionSerializer):
    class Meta:
        model = CrossCourse
        fields = "__all__"
        read_only_fields = read_only


# ResearchAward"序列化
class ResearchAwardSerializer(BaseCompetitionSerializer):
    class Meta:
        model = ResearchAward
        fields = "__all__"
        read_only_fields = read_only


# Paper"序列化
class PaperSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Paper
        fields = "__all__"
        read_only_fields = read_only


# Patent"序列化
class PatentSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Patent
        fields = "__all__"
        read_only_fields = read_only


# Monograph"序列化
class MonographSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Monograph
        fields = "__all__"
        read_only_fields = read_only


# TextBook"序列化
class TextBookSerializer(BaseCompetitionSerializer):
    class Meta:
        model = TextBook
        fields = "__all__"
        read_only_fields = read_only


# Cooperation"序列化
class CooperationSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Cooperation
        fields = "__all__"
        read_only_fields = read_only


# TextResearch"序列化
class TextResearchSerializer(BaseCompetitionSerializer):
    class Meta:
        model = TextResearch
        fields = "__all__"
        read_only_fields = read_only
# Meeting序列化
class MeetingSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Meeting
        fields = "__all__"
        read_only_fields = read_only

# Deduct"序列化
class DeductSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Deduct
        fields = "__all__"
        read_only_fields = read_only


# Other"序列化
class OtherSerializer(BaseCompetitionSerializer):
    class Meta:
        model = Other
        fields = "__all__"
        read_only_fields = read_only


serializer_dict = {}
for name in dir():
    if name != 'BaseCompetitionSerializer':
        serializer_dict[name] = eval(name)
